Grokking Amazon Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Amazon Easy Problems
Redistribute Characters to Make All Strings Equal (easy)
Solution: Redistribute Characters to Make All Strings Equal
Longest Common Prefix (easy)
Solution: Longest Common Prefix
Make Array Zero by Subtracting Equal Amounts (easy)
Solution: Make Array Zero by Subtracting Equal Amounts
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Path Crossing (easy)
Solution: Path Crossing
Special Array With X Elements Greater Than or Equal X (easy)
Solution: Special Array With X Elements Greater Than or Equal X
Relative Sort Array (easy)
Solution: Relative Sort Array
Transpose Matrix (easy)
Solution: Transpose Matrix
Find Common Characters (easy)
Solution: Find Common Characters
Fizz Buzz (easy)
Solution: Fizz Buzz
Increasing Order Search Tree (easy)
Solution: Increasing Order Search Tree
Largest Odd Number in String (easy)
Solution: Largest Odd Number in String
Best Time to Buy and Sell (easy)
Solution: Best Time to Buy and Sell Stock
Take Gifts From the Richest Pile(easy)
Solution: Take Gifts From the Richest Pile
Remove Duplicates from Sorted List (easy)
Solution: Remove Duplicates from Sorted List
Amazon Medium Problems
Maximum Length of Subarray With Positive Product (medium)
Solution: Maximum Length of Subarray With Positive Product
Largest Submatrix With Rearrangements (medium)
Solution: Largest Submatrix With Rearrangements
Count the Number of Good Subarrays (medium)
Solution: Count the Number of Good Subarrays
Minimum Suffix Flips (medium)
Solution: Minimum Suffix Flips
Minimum Number of Operations to Make Array Empty (medium)
Solution: Minimum Number of Operations to Make Array Empty
Next Greater Element II (medium)
Solution: Next Greater Element II
Make Sum Divisible by P (medium)
Solution: Make Sum Divisible by P
Rotting Oranges (medium)
Solution: Rotting Oranges
Minimum Deletions to Make Character Frequencies Unique (medium)
Solution: Minimum Deletions to Make Character Frequencies Unique
Minimum Adjacent Swaps to Make a Valid Array (medium)
Solution: Minimum Adjacent Swaps to Make a Valid Array
Reverse Integer (medium)
Solution: Reverse Integer
Maximize Distance to Closest Person (medium)
Solution: Maximize Distance to Closest Person
Split Linked List in Parts (medium)
Solution: Split Linked List in Parts
Maximum Difference Between Node and Ancestor (medium)
Solution: Maximum Difference Between Node and Ancestor
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
The kth Factor of n (medium)
Solution: The kth Factor of n
Coin Change II (medium)
Solution: Coin Change II
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Valid Sudoku (medium)
Solution: Valid Sudoku
Longest Increasing Subsequence (medium)
Solution: Longest Increasing Subsequence
Next Permutation (medium)
Solution: Next Permutation
Subsets (medium)
Solution: Subsets
Combination Sum (medium)
Solution: Combination Sum
Number of Provinces (medium)
Solution: Number of Provinces
Number of Islands (medium)
Solution: Number of Islands
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Number of Valid Subarrays (hard)
Solution: Number of Valid Subarrays
Count Vowels Permutation (hard)
Solution: Count Vowels Permutation
Concatenated Words (hard)
Solution: Concatenated Words
Minimum Replacements to Sort the Array (hard)
Solution: Minimum Replacements to Sort the Array
Count All Valid Pickup and Delivery Options (hard)
Solution: Count All Valid Pickup and Delivery Options
Length of the Longest Valid Substring (hard)
Solution: Length of the Longest Valid Substring
Count Array Pairs Divisible by K (hard)
Solution: Count Array Pairs Divisible by K
Word Ladder (hard)
Solution: Word Ladder
Path with Maximum Sum (hard)
Solution: Path with Maximum Sum
Solution: Rotting Oranges

Problem Statement

You are given an m x n matrix in which each cell can have one of three values:

  • 0 representing an empty cell,
  • 1 representing a fresh orange, or
  • 2 representing a rotten orange.

At each minute, any fresh orange becomes rotten if it is 4-directionally adjacent to a rotten orange.

Return the minimum number of minutes that should be passed until all the orange gets rotten. If it is impossible, return -1.

Examples

  • Input: grid =
[[2,1,0,0],
 [1,1,1,0],
 [0,1,1,1],
 [0,0,1,2]]
  • Expected Output: 3
  • Justification: The rotten oranges at (0,0) and (3,3) spread the rot to all adjacent fresh oranges. By day 4, all reachable fresh oranges are spoiled. The progression is as follows:
    • Minute 1: Oranges at positions (0, 1), (1, 0), (2, 3), and (3, 2) gets spoiled.
    • Minute 2: Oranges at positions (1, 1), and (2, 2) gets spoiled.
    • Minute 3: Oranges at positions (2, 1), and (1, 2) gets spoiled.

Example 2:

  • Input: grid =
[[2,1,1],
 [1,1,0],
 [0,1,2]]
  • Expected Output: 2
  • Justification: The rotten oranges spread the rot to all fresh oranges in 2 minutes, successfully spoiling all of them.

Example 3:

  • Input: grid =
[[0,2],
 [1,0],
 [0,1]]
  • Expected Output: -1
  • Justification: In any case, it is not possible that all oranges gets rotten.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 10
  • grid[i][j] is 0, 1, or 2.

Solution

To solve this problem, we'll use a breadth-first search (BFS) approach, treating the grid as a graph where each cell is a node connected to its adjacent (up, down, left, right) cells. This method is effective because it allows us to spread the rot from all rotten oranges simultaneously, day by day, mimicking the natural process of spoilage spreading. By tracking the days as levels in our BFS traversal, we can determine the minimum time required to spoil all reachable fresh oranges or identify if any remain unreachable and thus, unsolvable.

Our approach starts by identifying all the initial rotten oranges and adding them to a queue as the starting point of our BFS. We also count the number of fresh oranges to keep track of the progress. On each day (or level of BFS), we take the current rotten oranges from the queue, spoil their adjacent fresh oranges, and then add those newly rotten oranges to the queue for the next day's process. This continues until either there are no fresh oranges left or we cannot reach any more fresh oranges, indicating an unsolvable situation.

Step-by-Step Algorithm

  1. Initialize a queue to keep track of the positions (row and column) of all initially rotten oranges. Also, maintain a counter to keep track of the number of fresh oranges present in the grid.

  2. Iterate over the grid to find and add all initially rotten oranges' positions to the queue and count the number of fresh oranges. This step helps to understand the starting point of the problem and the goal to achieve (i.e., to rot all fresh oranges, if possible).

  3. Perform a breadth-first search (BFS) from all initially rotten oranges simultaneously:

    • Increment a minute counter at the start of each level of BFS (each level represents a minute).
    • For each rotten orange in the queue, check its four adjacent cells (up, down, left, right). If an adjacent cell contains a fresh orange (denoted by 1), change it to a rotten orange (denoted by 2), decrement the fresh orange counter, and add its position to the queue for processing in the next minute.
    • Continue this process until the queue is empty or there are no more fresh oranges left to rot.
  4. After the BFS completion, check if there are any fresh oranges left:

    • If no fresh oranges are left (fresh orange counter is 0), return the total minutes elapsed as the result.
    • If there are still fresh oranges left, return -1 to indicate that not all oranges can be rotted.

Algorithm Walkthrough

Initial Setup

  • Grid:
    [[2,1,0,0],
     [1,1,1,0],
     [0,1,1,1],
     [0,0,1,2]]
    
  • Rotten Oranges Queue: [(0,0), (3,3)] (positions of initially rotten oranges).
  • Fresh Oranges Count: 8.

Minute 0: Start with two rotten oranges in the queue.

  • Queue: [(0,0), (3,3)]
  • Fresh Oranges: 8

Minute 1: Process the first level of the queue.

  • Dequeue (0,0). It rots the oranges at positions (1,0) and (0,1).
  • Dequeue (3,3). It rots the oranges at positions (2,3) and (3,2).
  • New rotten oranges added to the queue: [(1,0), (0,1), (2,3), (3,2)].
  • Grid After Minute 1:
    [[2,2,0,0],
     [2,1,1,0],
     [0,1,1,2],
     [0,0,2,2]]
    
  • Fresh Oranges: 4

Minute 2: Process the second level of the queue.

  • Dequeue and process (1,0), (0,1), (2,3), and (3,2). From these, only (1,0) and (2,3) have adjacent fresh oranges they can rot, specifically:
    • (0,1) directly rots (1,1).
    • (1,0) has no more fresh oranges to rot adjacent to it.
    • (2,3) rots (2,2).
    • (3,2) has no more fresh oranges to rot adjacent to it.
  • New rotten oranges added to the queue: [(1,1), (2,2)].
  • Grid After Minute 2:
    [[2,2,0,0],
     [2,2,1,0],
     [0,1,2,2],
     [0,0,2,2]]
    
  • Fresh Oranges: 2

Minute 3: Process the third level of the queue.

  • Dequeue and process (1,1) and (2,2). These new rotten oranges can rot the remaining fresh oranges at (2,1) and (1,2).
  • New rotten oranges added to the queue: [(2,1), (1,2)].
  • Grid After Minute 3:
    [[2,2,0,0],
     [2,2,2,0],
     [0,2,2,2],
     [0,0,2,2]]
    
  • Fresh Oranges: 0

Conclusion: By the end of Minute 3, all reachable fresh oranges have been spoiled, and the grid no longer contains any fresh oranges.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

  • Time Complexity: The time complexity is , where (M) and (N) are the dimensions of the grid. This is because, in the worst case, each cell is visited at least once.
  • Space Complexity: The space complexity is in the worst case due to the queue potentially holding all the oranges if they are all rotten initially.
Rotting Oranges (medium)
Minimum Deletions to Make Character Frequencies Unique (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Initial Setup

Code

Complexity Analysis